<?php

class Import extends PW_Model{

	public function __construct(){
		parent::__construct();
	}

	public function do_import($path_file= '', array $structure_file = null, $table = ''){
		if(empty($structure_file) || empty($path_file) || empty($table)){
			return false;
		}

		$query = $this->create_query_import($path_file, $structure_file, $table);
		if(!$this->db->query($query)){
			return false;
		}

		return true;
	}

	public function create_query_import($path_file, $structure_file = null, $table = ''){
		if(empty($structure_file) || empty($path_file) || empty($table)){
			return false;
		}

		$query = "LOAD DATA LOCAL INFILE '{$path_file}'
					INTO TABLE {$table} LINES STARTING BY '<row>' TERMINATED BY '</row>'
					(@person)
					SET ";

		foreach($structure_file as $item){
			$query .= " {$item}	= 	SUBSTRING(@person,
						@temp:=LOCATE('<{$item}>', @person) + LENGTH('<{$item}>'),
						LOCATE('</{$item}>', @person) - @temp),";
		}

		$query.= " create_datetime = NOW(),
				   lastup_datetime = NOW();";

		return $query;
	}

	public function get_fields_table($table = ''){
		if(!$table){
			return false;
		}

		return $this->db->list_fields($table);
	}

	public function is_existed_field($table = '', $field = ''){
		if(!$field || !$table){
			return false;
		}

		return (bool)$this->db->field_exists($field, $table);
	}

	public function is_existed_table($table = '') {
		if(!$table){
			return false;
		}

		return (bool)$this->db->table_exists($table);
	}
}